package com.ssm.juc.thread;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.*;

public class ThreadPoolTest2 {

    /*
    @Value("${corePoolSize:2}")
    private Integer corePoolSize;
    @Value("${corePoolSize:8}")
    private Integer maximumPoolSize;

    public static void main(String[] args) {
        ThreadPoolExecutor taskExecutor = new ThreadPoolExecutor(8, 64, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>(256),
                new ThreadFactoryBuilder().setNameFormat("customer-worker-%d").build(),
                (task, executor) -> {
                    try {
                        executor.getQueue().put(task);
                    } catch (InterruptedException e) {
                        logger.error("customer-worker 线程阻断异常:" + e.getMessage(), e);
                    }
                });


        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaximumPoolSize(maximumPoolSize);
    }
     */

    public static void main(String[] args) throws InterruptedException {
        //semaphoreLimitSubmitThread();

        countDownLatchCheck();
    }

    private static void countDownLatchCheck() {
        //创建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 20,
                0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1024));

        CountDownLatch countDownLatch = new CountDownLatch(2);

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            threadPool.submit(() -> {

                try {
                    // 随机休眠 0-4s
                    int sleepTime = new Random().nextInt(5);
                    TimeUnit.SECONDS.sleep(Math.max(sleepTime, 2));
                } catch (InterruptedException e) {
                    System.err.println("InterruptedException err : " + e.getMessage());
                }

                System.out.println(gettime() + " task running : " + finalI);
                countDownLatch.countDown(); // 每次计数器-1
            });
        }
        try {
            countDownLatch.await(); // 等待所有的任务执行完毕
        } catch (InterruptedException t) {
            System.err.println("InterruptedException err : " + t.getMessage());
        }
    }

    private static void semaphoreLimitSubmitThread() {
        // 创建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 20,
                0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1024));
        final int taskCount = 5;    // 任务总数
        // 循环计数器
        Semaphore semaphore = new Semaphore(2);
        // 添加任务
        for (int i = 0; i < taskCount; i++) {
            final int finalI = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 获取信号量
                        semaphore.acquire();

                        // 随机休眠 4s
                        TimeUnit.SECONDS.sleep(4);
                        System.out.println(String.format("%s 任务%d执行完成", gettime(), finalI));

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        semaphore.release();
                    }
                }
            });
        }
    }

    @NotNull
    private static String gettime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = sdf.format(new Date());
        return format1;
    }
}
